(function (window) {
  //"use strict";

  function HangoutDemo() {
    console.log("Starting...");
	gapi.hangout.onApiReady.add(this.onApiReady.bind(this));	// Add callback
  }
  
  HangoutDemo.prototype.onApiReady = function (event) {	
    if (event.isApiReady === true) {	
      console.log("API Ready");	
      gapi.hangout.onParticipantsChanged.add(	// add callback for event
        this.onParticipantsChanged.bind(this)	
      );
	  
	  gapi.hangout.onParticipantsRemoved.add(	// add callback for event
        this.onParticipantsRemoved.bind(this)	
      );
	this.displayParticipants();
    }	
  };
  
  /* Update the div when the participant changes */
  HangoutDemo.prototype.onParticipantsChanged = function (event) {	
    var div = document.getElementById("appcontainer");	
    div.innerHTML = "";	// make sure our container is empty before displaying the list
    this.displayParticipants();	
  };
  
  /* Update the div when the participant changes */
  HangoutDemo.prototype.onParticipantsRemoved = function (event) {	
    console.log("Participant Removed");
	top.window.close();
  };
  
  /* display participants*/
  HangoutDemo.prototype.displayParticipants = function () {	
    var div, participants, ul, li, i, l;	
    participants = gapi.hangout.getParticipants();	// Get array of participants from API
    ul = document.createElement("ul");	
    l = participants.length;
    for (i = 0; i < l; i++) {	
      li = document.createElement("li");	
      if (participants[i].person) {	
        li.innerHTML = participants[i].person.displayName;	// Add name to list if available
      } else {	
        li.innerHTML = "unknown";	
      }	
      ul.appendChild(li);	
    }	
    div = document.getElementById("appcontainer");	
    div.appendChild(ul);	
  };

  var hangoutDemo = new HangoutDemo();
}(window));
